class ProfilesController < ApplicationController
  
  PICTURE_DIR = "#{RAILS_ROOT}/public/pictures"
  VALID_IMAGE_FORMATS = ['image/jpeg', 'image/png', 'image/gif']
  MAXIMUM_IMAGE_SIZE = 2 * 1024 * 1024
  
  before_filter :check_authentication, :except => [:biography]
  
  def biography
    find_user_and_render_public_page
  end
  
  def update
    @profile = @user.profile || Profile.new
    if request.post?
      @profile.attributes = params[:profile]
      @profile.user = @user
      @profile.save!
      
      flash[:notice] = "Your profile has been updated"
      redirect_to :action => "update"
    end
  rescue ActiveRecord::RecordNotFound
    redirect_to :controller => 'users', :action => 'signin'    
  end
  
  def upload_picture
    if request.post?
      if !VALID_IMAGE_FORMATS.include?(params[:profile][:picture].content_type.chomp) 
        flash[:notice] = "You can only upload images with format: gif, jpg or png"
      elsif params[:profile][:picture].size > MAXIMUM_IMAGE_SIZE
        flash[:notice] = "You can only upload images under 2M"
      else
        user_picture_dir = "#{PICTURE_DIR}/#{session[:user]}"
        Dir.mkdir(user_picture_dir) unless File.exist?(user_picture_dir)
        remove_previous_images(user_picture_dir)
        File.open("#{user_picture_dir}/#{params[:profile][:picture].original_filename}", "wb") do |f| 
          f.write(params[:profile][:picture].read) 
        end
      end
    end
    redirect_to :action => "update"
  end
  
  private 
  def remove_previous_images(dir)
    Dir.new(dir).each do |image|
      image_path = File.join(dir, image);
      File.delete(image_path) if File.ftype(image_path) == "file"
    end
  end
  
end